package com.chuangjiangx.member.manager.web.web.stored.controller;

import com.chuangjiangx.commons.CJBeanUtils;
import com.chuangjiangx.commons.exception.BaseException;
import com.chuangjiangx.commons.response.Response;
import com.chuangjiangx.commons.response.ResponseUtils;
import com.chuangjiangx.member.coupon.ddd.dal.dto.MbrCouponDetail;
import com.chuangjiangx.member.coupon.ddd.domain.model.MbrCouponType;
import com.chuangjiangx.member.coupon.ddd.query.MbrCouponQuery;
import com.chuangjiangx.member.manager.basic.web.controller.BaseController;
import com.chuangjiangx.member.manager.basic.web.interceptor.Login;
import com.chuangjiangx.member.manager.common.BeanUtils;
import com.chuangjiangx.member.manager.common.Constants;
import com.chuangjiangx.member.manager.common.ThreadLocalUser;
import com.chuangjiangx.member.manager.web.web.stored.request.CreateStoredRulesRequest;
import com.chuangjiangx.member.manager.web.web.stored.request.DeleteStoredRuleRequest;
import com.chuangjiangx.member.manager.web.web.stored.request.DisableStoredRulesRequest;
import com.chuangjiangx.member.manager.web.web.stored.request.EnableStoredRulesRequest;
import com.chuangjiangx.member.manager.web.web.stored.response.CustomRechargeResponse;
import com.chuangjiangx.member.manager.web.web.stored.response.StoredRulesListForMerchantResponse;
import com.chuangjiangx.member.stored.ddd.application.MbrRechargeRuleApplication;
import com.chuangjiangx.member.stored.ddd.application.command.CreateRechargeRuleCommand;
import com.chuangjiangx.member.stored.ddd.application.command.DeleteRechargeRuleCommand;
import com.chuangjiangx.member.stored.ddd.application.command.DisableRechargeRuleCommand;
import com.chuangjiangx.member.stored.ddd.application.command.EnableRechargeRuleCommand;
import com.chuangjiangx.member.stored.ddd.dal.dto.RechargeRuleList;
import com.chuangjiangx.member.stored.ddd.domain.model.MbrGiftType;
import com.chuangjiangx.member.stored.ddd.query.MbrRechargeRuleQuery;
import com.chuangjiangx.member.stored.ddd.query.dto.CustomRechargeDTO;
import com.chuangjiangx.member.stored.ddd.query.dto.RechargeRuleListForMerchantDTO;
import com.sun.jmx.snmp.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * 储值规则管理
 * Created by YangKuo on 2017/11/27.
 */
@RestController
@RequestMapping(value = "/api/mbr/stored", produces = "application/json")
public class MbrRechargeRuleController extends BaseController {
    @Autowired
    private MbrRechargeRuleQuery mbrRechargeRuleQuery;
    @Autowired
    private MbrRechargeRuleApplication mbrRechargeRuleApplication;
    @Autowired
    private MbrCouponQuery mbrCouponQuery;

    /**
     * 储值规则列表
     *
     * @param session 获取用户信息session
     * @return 列表
     * @map storedRulesList
     * @see StoredRulesListForMerchantResponse
     */
    @RequestMapping(value = "/searchStoredRulesList")
    @Login
    public Response searchStoredRulesList() {


        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        //对象转换
        List<RechargeRuleListForMerchantDTO> list = mbrRechargeRuleQuery.queryRulesListForMerchant(user.getMerchantId());
        List<StoredRulesListForMerchantResponse> responses = BeanUtils.convertCollection(list, StoredRulesListForMerchantResponse.class, (s, t) -> {
            String ruleName;
            if (MbrGiftType.AMOUNT.value == s.getGiftType()) {
                ruleName = "充" + s.getAmount() + "元赠送" + s.getGiftAmount() + "元";
            } else if (MbrGiftType.SCROE.value == s.getGiftType()) {
                ruleName = "充" + s.getAmount() + "元赠送" + s.getGiftScore() + "积分";
            } else {
                ruleName = "充" + s.getAmount() + "元赠送" + s.getGiftCoupon();
            }
            t.setRuleName(ruleName);
        });
        return ResponseUtils.success("storedRulesList", responses);
    }

    /**
     * 新增储值规则
     *
     * @param session      获取用户信息session
     * @param rulesRequest 储值规则信息
     * @return 新增结果
     */
    @RequestMapping(value = "/createStoredRule")
    @Login
    public Response createStoredRules(@RequestBody @Validated CreateStoredRulesRequest rulesRequest) throws Exception {

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        String name = null;
        if(rulesRequest.getGiftType()==MbrGiftType.COUPON.value){
            MbrCouponDetail couponDetail = mbrCouponQuery.getMbrCouponDetailInfo(rulesRequest.getCouponNumber());
            if(null == couponDetail){
                throw new BaseException("","卡券不存在");
            }
            MbrCouponType type = MbrCouponType.getType(couponDetail.getType());

            switch (type){
                case EXCHANGE_COUPON:
                    name = couponDetail.getName();
                    break;
                case ONSALE_COUPONS:
                    name = couponDetail.getAmount() + "折折扣券";
                    break;
                case CASH_COUPON:
                    name = couponDetail.getAmount().stripTrailingZeros().toEngineeringString() + "元代金券";
                    break;
                default:
                    break;
            }
        }

        //新增储值规则信息
        CreateRechargeRuleCommand command = new CreateRechargeRuleCommand(
                rulesRequest.getName(),
                rulesRequest.getAmount(),
                rulesRequest.getGiftScore(),
                rulesRequest.getGiftAmount(),
                rulesRequest.getCouponNumber(),
                name,
                rulesRequest.getEnable(),
                rulesRequest.getGiftType(),
                user.getMerchantId()
        );
        mbrRechargeRuleApplication.createRechargeRule(command);
        return ResponseUtils.success();
    }

    /**
     * 启用储值规则
     *
     * @param rulesRequest 请求参数
     * @param session      获取用户信息session
     * @return 启用结果
     * @throws Exception
     */
    @RequestMapping(value = "/enableStoredRules")
    @Login
    public Response enableStoredRules(@RequestBody @Validated EnableStoredRulesRequest rulesRequest, HttpSession session) throws Exception {

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        EnableRechargeRuleCommand command = new EnableRechargeRuleCommand(
                rulesRequest.getEnable(),
                rulesRequest.getStoredRulesId(),
                user.getMerchantId()
        );
        mbrRechargeRuleApplication.enableRechargeRule(command);
        return ResponseUtils.success();
    }

    /**
     * 禁用储值规则
     *
     * @param rulesRequest 请求参数
     * @param session      获取用户信息session
     * @return 禁用结果
     * @throws Exception
     */
    @RequestMapping(value = "/disableStoredRules")
    @Login
    public Response disableStoredRules(@RequestBody @Validated DisableStoredRulesRequest rulesRequest, HttpSession session) throws Exception {

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        DisableRechargeRuleCommand command = new DisableRechargeRuleCommand(
                rulesRequest.getEnable(),
                rulesRequest.getStoredRulesId(),
                user.getMerchantId()
        );
        mbrRechargeRuleApplication.disableRechargeRule(command);
        return ResponseUtils.success();
    }

    /**
     * 删除储值规则
     *
     * @param ruleRequest 请求参数
     * @param session     获取用户信息session
     * @return 删除结果
     */
    @RequestMapping(value = "/deleteStoredRules")
    @Login
    public Response deleteStoredRules(@RequestBody @Validated DeleteStoredRuleRequest ruleRequest, HttpSession session) throws Exception {

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        DeleteRechargeRuleCommand command = new DeleteRechargeRuleCommand(
                ruleRequest.getEnable(),
                ruleRequest.getStoredRulesId(),
                user.getMerchantId()
        );
        mbrRechargeRuleApplication.delRechargeRule(command);
        return ResponseUtils.success();
    }

    /**
     * 自定义储值规则开关状态
     *
     * @param session 获取用户信息session
     * @return 开关状态
     * @see CustomRechargeResponse
     */
    @RequestMapping(value = "/checkRulesOpen")
    @Login
    public Response searchRulesOpenStatus(HttpSession session) {

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        CustomRechargeDTO dto = mbrRechargeRuleQuery.checkRulesOpen(user.getMerchantId());
        CustomRechargeResponse rulesOpenStatus = new CustomRechargeResponse();
        CJBeanUtils.convertBean(dto, rulesOpenStatus);
        return ResponseUtils.success(rulesOpenStatus);
    }

    /**
     * 开启自定义储值规则
     *
     * @param session 获取用户信息session
     * @return 开启结果
     */
    @RequestMapping(value = "/openCustomRecharge")
    @Login
    public Response openCustomRecharge(HttpSession session) {
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        mbrRechargeRuleApplication.openRechargeRule(user.getMerchantId());
        return ResponseUtils.success();
    }

    /**
     * 关闭自定义储值规则开关
     *
     * @param session 获取用户信息session
     * @return 关闭结果
     */
    @RequestMapping(value = "/closeCustomRecharge")
    public Response closeCustomRecharge(HttpSession session) throws Exception {
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        mbrRechargeRuleApplication.closeRechargeRule(user.getMerchantId());
        return ResponseUtils.success();
    }

    /**
     * 最大储值规则
     *
     * @param merchantId 商户id
     */
    @RequestMapping(value = "/gift-amount-max-name")
    public Response getMaxGiftRule(Long merchantId) {
        List<RechargeRuleList> ruleLists = mbrRechargeRuleQuery.queryRulesList(merchantId);
        Optional<RechargeRuleList> optional = ruleLists.stream()
                .filter(r -> r.getGiftType() == MbrGiftType.AMOUNT.value)
                .sorted(Comparator.comparing(r -> r.getGiftAmount(), Comparator.reverseOrder()))
                .findFirst();
        optional.ifPresent(o -> o.setName("充"+o.getAmount().stripTrailingZeros().toPlainString()+"元送"+o.getGiftAmount().stripTrailingZeros().toPlainString()+"元"));
        return ResponseUtils.success(optional.orElse(null));
    }
}
